package cn.fl.carloan.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.SimpleFormatter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import cmm.comm.facade.upload.constant.SysUlFilesRecConstant;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.carloan.service.IOdrWechatpictRecService;
import cn.fl.carloan.transform.OdrWechatpictRecVOTransform;
import cn.fl.carloan.vo.OdrWechatpictRecVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.ref.fncprjbscinfo.util.DateUtil;
import fl.carloan.facade.carloan.condition.OdrWechatpictRecQC;
import fl.carloan.facade.carloan.dto.OdrWechatpictRecDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;

/**
 * @Description: 微信画报附件信息表 控制层
 */
@Controller
@RequestMapping("/carloan/odrwechatpictrec")
public class OdrWechatpictRecController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(OdrWechatpictRecController.class);

    /**
     * OdrWechatpictRec 服务层BEAN
     */
    @Autowired
    private IOdrWechatpictRecService odrWechatpictRecService;


    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toListPage", "加载列表页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        ModelAndView view = new ModelAndView("carloan/odrWechatPictRec/toListPage");

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toListPage", "加载列表页面.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 到新增修改页面
     */
    @RequestMapping(value = "/toAddPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toAddPage", "加载新增.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        ModelAndView view = new ModelAndView("carloan/odrWechatpictRec/odrWechatpictRecAdd");

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toAddPage", "加载新增.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 到修改页面
     */
    @RequestMapping(value = "/toModifyPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {

        String id = request.getParameter("id");
        ModelAndView view = new ModelAndView("carloan/odrWechatPictRec/odrWechatpictRecModify");
        OdrWechatpictRecVO entity = new OdrWechatpictRecVO();
        if (StringUtils.isNotEmpty(id)) {
            entity = this.odrWechatpictRecService.selectById(Long.valueOf(id));
        }
        //List<KeyValueVO> syscdlist = this.cmsBnrDcService.getKvListWithAttr1AndAttr2(DictionaryConstant.CODE_SYS_DS_CD,"",DictionaryConstant.CODE_SYS_CODE_ATTR2_CD,CurrentThreadContext.getFlServiceSysCd(),CurrentThreadContext.getCurrentOrgCd());
        //view.addObject("syscdlist",syscdlist);
        view.addObject("wechatPicRec", entity);
        view.addObject("serverpath", PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_SERVER_PATH));
        BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
        return view;

    }

    /**
     * 到详情页面
     */
    @RequestMapping(value = "/toDetailPage.do", method = {RequestMethod.GET})
    public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toDetailPage", "加载例子详细页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String id = request.getParameter("id");
        ModelAndView view = new ModelAndView("carloan/odrWechatpictRec/odrWechatpictRecDetail");
        view.addObject("id", id);

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toDetailPage", " 加载例子详细页面.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initList(HttpServletRequest request, HttpServletResponse response) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        ListPageVO<OdrWechatpictRecVO> listPage = null;
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "initList", "加载列表页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());


        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        String pictStatus = request.getParameter("pictStatus");
        String pictNickNm = request.getParameter("pictNickNm");
        String beginTime = request.getParameter("beginTime");
        String endTime = request.getParameter("endTime");
        try {
            OdrWechatpictRecQC qc = new OdrWechatpictRecQC();
            if (StringUtils.isNotEmpty(beginTime)) {
                Date dateByStringTime = DateUtil.getDateByStringTime(beginTime);
                // Date dateAddDate = DateUtils.getDateAddDate(dateByStringTime, 5, -1);
                String format = sdf.format(dateByStringTime);
                Date parse = sdf.parse(format);
                qc.setBeginTime(parse);
            }
            if (StringUtils.isNotEmpty(endTime)) {
                Date dateByStringTime = DateUtil.getDateByStringTime(endTime);
                //  Date dateAddDate = DateUtils.getDateAddDate(dateByStringTime, 5, -1);
                String format = sdf.format(dateByStringTime);
                Date parse = sdf.parse(format);
                qc.setEndTime(parse);
            }
            if (StringUtils.isNotEmpty(pictStatus)) {
                qc.setPictStatus(Integer.valueOf(pictStatus));
            }
            if (StringUtils.isNotEmpty(pictNickNm)) {
                qc.setPictNickNm(pictNickNm);
            }

            Pager page = new Pager();
            if (StringUtils.isNotEmpty(currentPage)) {
                page.setCurrentPage(Integer.parseInt(currentPage));
            }

            if (StringUtils.isNotEmpty(pageSize)) {
                page.setEveryPage(Integer.parseInt(pageSize));
            }
            page.setCondition(qc);
            //TODO SOMETHING
            Pager pager = this.odrWechatpictRecService.searchListPage(page);
            List<OdrWechatpictRecDTO> resultList = (List<OdrWechatpictRecDTO>) pager.getResultList();
            List<OdrWechatpictRecVO> list = OdrWechatpictRecVOTransform.toVOList(resultList);
            if (CollectionUtils.isNotEmpty(resultList)) {
                for (OdrWechatpictRecVO odrWechatpictRecVO : list) {
                    if (odrWechatpictRecVO.getPictStatus() == 0) {
                        odrWechatpictRecVO.setPictStatusNm("隐藏");
                    } else if (odrWechatpictRecVO.getPictStatus() == 1) {
                        odrWechatpictRecVO.setPictStatusNm("展示");
                    }
                    odrWechatpictRecVO.setCrtNum(odrWechatpictRecVO.getCrtNum() == null ? 0L : odrWechatpictRecVO.getCrtNum());
                }
            }
            listPage = new ListPageVO<OdrWechatpictRecVO>(list, pager.getTotalCount());
        } catch (Exception e) {
            e.printStackTrace();

        }

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "initList", "加载列表页面.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return listPage;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "add", "新增对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String name = request.getParameter("name");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
        OdrWechatpictRecVO entity = null;
        try {
            entity = new OdrWechatpictRecVO();
            //TODO ADD PARAM
            Long id = this.odrWechatpictRecService.add(entity);
            result.setData(id);
            BaseLogUtils.info(logger, "add", "新增数据.[id=" + id + "] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "add", "新增对象失败,name[" + name + "].", CurrentThreadContext.getCurrentUserName(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.error(logger, "add", "新增对象失败,name[" + name + "].", CurrentThreadContext.getCurrentUserName(), ex);
        }
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "add", "新增对象.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());

        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/modify.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "modify", "修改对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String id = request.getParameter("pictId");
        String pictNickNm = request.getParameter("pictNickNm");
        String pictSortNo = request.getParameter("pictSortNo");
        String pictUrl = request.getParameter("pictUrl");
        String pictStatus = request.getParameter("pictStatus");//0: 隐藏 1：展示
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "修改成功!");
        try {
            OdrWechatpictRecVO entity = null;
            if (StringUtils.isNotEmpty(pictUrl)) {
                int i = pictUrl.lastIndexOf(".");
                String s = pictUrl.substring(i+1, pictUrl.length()).toUpperCase();
                System.out.println("============================文件后缀为：--》"+s);
                if (StringUtils.isNotEmpty(s)) {
                    if (!s.equals("JPG") && !s.equals("JPEG") && !s.equals("PNG") && !s.equals("BMP")) {
                        result.setSuccess(0);
                        result.setInfo("只能上传 JPG、JPEG、PNG、BMP类型的图片！");
                        return result;
                    }

                }
            }
            if (StringUtils.isEmpty(id)) {
                //如果ID为空则为新增！
                entity = new OdrWechatpictRecVO();
                if (pictNickNm.length() > 8) {
                    result.setSuccess(0);
                    result.setInfo("海报名称不能超过八个字符！");
                    return result;
                }
                if(StringUtils.isEmpty(pictUrl)){
                    result.setSuccess(0);
                    result.setInfo("请选择图片点击上传！");
                    return result;
                }
                entity.setPictNickNm(pictNickNm);
                entity.setPictSortNo(pictSortNo);
                entity.setPictUrl(pictUrl);
                entity.setPictStatus(Integer.valueOf(pictStatus));
                entity.setCrtNum(0L);
                entity.setIsDel(0);
                //在添加新的海报记录的时候先吧序号以后的加一
                OdrWechatpictRecQC condition = new OdrWechatpictRecQC();
                condition.setPictSortNo(pictSortNo);
                List<OdrWechatpictRecDTO> list = odrWechatpictRecService.selectList(condition);
                if (CollectionUtils.isNotEmpty(list)) {
                    odrWechatpictRecService.increaseOneSort(condition);
                }
                Long recId = this.odrWechatpictRecService.add(entity);
                List<OdrWechatpictRecDTO> odrWechatpictRecDTOS = odrWechatpictRecService.selectList(new OdrWechatpictRecQC());
                if (CollectionUtils.isNotEmpty(odrWechatpictRecDTOS)) {
                    for (int i = 0; i < odrWechatpictRecDTOS.size(); i++) {
                        OdrWechatpictRecVO vo = new OdrWechatpictRecVO();
                        vo.setPictSortNo(i + 1 + "");
                        vo.setId(Long.valueOf(odrWechatpictRecDTOS.get(i).getId()));
                        odrWechatpictRecService.modify(vo);
                    }
                }
                BaseLogUtils.info(logger, "add", "新增海报对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
                result.setData(recId);
                result.setInfo("新增成功");
                return result;
            }

            entity = new OdrWechatpictRecVO();
            entity.setId(Long.valueOf(id));
            entity.setPictStatus(Integer.valueOf(pictStatus));
            entity.setPictNickNm(pictNickNm);
            entity.setPictUrl(pictUrl);
            entity.setPictSortNo(pictSortNo);
            entity.setIsDel(0);
            entity.setMdfTm(new Date());
            OdrWechatpictRecQC condition = new OdrWechatpictRecQC();
            condition.setPictSortNo(pictSortNo);
            OdrWechatpictRecVO odrWechatpictRecVO = odrWechatpictRecService.selectById(Long.valueOf(id));
            if (StringUtils.isNotEmpty(pictSortNo) && !pictSortNo.equals(odrWechatpictRecVO.getPictSortNo())) {
                List<OdrWechatpictRecDTO> list = odrWechatpictRecService.selectList(condition);
                if (StringUtils.isNotEmpty(pictSortNo) && CollectionUtils.isNotEmpty(list)) {
                    odrWechatpictRecService.increaseOneSort(condition);
                }
            }
            boolean success = this.odrWechatpictRecService.modify(entity);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("修改失败!");
                BaseLogUtils.info(logger, "modify", "修改失败.[id=" + id + "] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
            } else {
                if(StringUtils.isNotEmpty(pictSortNo)){
                    List<OdrWechatpictRecDTO> odrWechatpictRecDTOS = odrWechatpictRecService.selectList(new OdrWechatpictRecQC());
                    if (CollectionUtils.isNotEmpty(odrWechatpictRecDTOS)) {
                        for (int i = 0; i < odrWechatpictRecDTOS.size(); i++) {
                            OdrWechatpictRecVO vo = new OdrWechatpictRecVO();
                            vo.setPictSortNo(i + 1 + "");
                            vo.setId(Long.valueOf(odrWechatpictRecDTOS.get(i).getId()));
                            odrWechatpictRecService.modify(vo);
                        }
                    }
                }
            }
            BaseLogUtils.info(logger, "modify", "修改成功.[id=" + id + "] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "modify", "修改对象失败,id[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.error(logger, "modify", "修改对象失败,id[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        }

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "modify", "修改对象.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());

        return result;
    }

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeById.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "remove", "移除对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "删除成功!");
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("主键不能为空!");
            return result;
        }
        try {
            this.odrWechatpictRecService.removeById(Long.valueOf(id));
            BaseLogUtils.info(logger, "removeById", "删除数据.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "remove", "移除对象失败,主键[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.error(logger, "remove", "移除对象失败,主键[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        }

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "remove", "移除对象.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());

        return result;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "getById", "根据主键获取对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("主键不能为空!");
            BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        try {
            OdrWechatpictRecVO vo = this.odrWechatpictRecService.selectById(Long.valueOf(id));
            if (null == vo) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("数据不存在!");
                BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
            }
            result.setData(vo);
            BaseLogUtils.info(logger, "getById", "获取数据.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "getById", "根据主键获取对象失败,主键[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.error(logger, "getById", "根据主键获取对象失败,主键[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        }

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "getById", "根据主键获取对象.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());

        return result;
    }
}

